package com.mifengs.mall.ui.opencompany;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.mall.adapter.ContractRvAdapter;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.entity.ContractPre;
import com.mifengs.mall.entity.ImageUpload;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.event.OpenCompanyEvent;
import com.mifengs.mall.loader.GlideImageLoader;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.util.UploadImgUtil;
import com.mifengs.mall.widget.FullyGridLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 *  合同提交页面
 */
public class ContractFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks {


    @BindView(R.id.rv_photo)
    RecyclerView mRvPhoto;
    @BindView(R.id.bt_submit)
    Button mBtSubmit;

    private ContractRvAdapter mRvAdapter;

    private ArrayList<ImageItem> mImageItems;
    private int mCurrentPos = 0;
    private ImagePicker mImagePicker;
    private ArrayList<ImageItem> mResultImages = new ArrayList<>();
    public static final int REQUEST_PERMISSION_CAMERA = 1;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int maxImgCount = 5;
    private ImageItem mAddItem = new ImageItem();
    private boolean isUploading = false;
    private String mContractDownUrl;
    private String mContractPreUrl;

    public ContractFragment() {
        // Required empty public constructor
    }

    public static ContractFragment newInstance() {
        ContractFragment fragment = new ContractFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contract, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mImageItems = new ArrayList<>();
        mImageItems.add(new ImageItem());
        mRvAdapter = new ContractRvAdapter();
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(getContext(), 3);
        mRvPhoto.setLayoutManager(gridLayoutManager);
        mRvPhoto.setAdapter(mRvAdapter);
        mRvAdapter.setNewData(mImageItems);
        checkIsCanSubmit();
        mRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mCurrentPos = position;
                if (mCurrentPos == (mImageItems.size() - 1) && isHaveAddItem()) {
                    if (isUploading) {
                        ToastUitl.showLong("正在上传图片");
                    } else {
                        needCamera();
                    }
                } else {
                    if (!isUploading)
                        startPreview(position);
                }
            }
        });
        mRvAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                showDeleteDialog(position);

//                mImageItems.remove(position);
//                if(!isHaveAddItem()){
//                    mImageItems.add(mAddItem);
//                };
//                mRvAdapter.notifyDataSetChanged();
            }
        });
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void needCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            choosePhoto();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.need_camera_permission),
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }

    private void choosePhoto() {
        mImagePicker = ImagePicker.getInstance();
        mImagePicker.setImageLoader(new GlideImageLoader());
        mImagePicker.setMultiMode(true);
        mImagePicker.setShowCamera(true);
        mImagePicker.setCrop(false);
        mImagePicker.setSelectLimit(maxImgCount + 1 - mImageItems.size());
        Intent intent = new Intent(getActivity(), ImageGridActivity.class);
        getActivity().startActivityForResult(intent, 100);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                mResultImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                setAndUpLoadImg();
            } else {
                Toast.makeText(getContext(), "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                images.add(mAddItem);
                this.mImageItems = images;
                mRvAdapter.setNewData(mImageItems);
                checkIsCanSubmit();
            }
        }
    }


    private void setAndUpLoadImg() {
        upLoadImage(mResultImages);
    }

    ImageItem mCurrUpImageItem;
    int mCurrUpIndex;

    private void upLoadImage(final ArrayList<ImageItem> imageItems) {
        Observable.from(imageItems)
                .compose(this.<ImageItem>bindToLife())
                .concatMap(new Func1<ImageItem, Observable<ImageUpload>>() {
                    @Override
                    public Observable<ImageUpload> call(ImageItem imageItem) {
                        isUploading = true;
                        String s = imageItem.path;
                        mCurrUpIndex = imageItems.indexOf(imageItem);
                        mCurrUpImageItem = imageItem;
                        LogUtil.i("ContractFragment:", "上传照片顺序 " + mCurrUpIndex);
                        if (isHaveAddItem()) {
                            mImageItems.remove(mImageItems.size() - 1);
                        }
                        mImageItems.add(mCurrUpImageItem);
                        if (mImageItems.size() < maxImgCount) {
                            mImageItems.add(mAddItem);
                        }
                        mRvAdapter.notifyDataSetChanged();
                        return UploadImgUtil.upCompressImg(s);
                    }
                })
                .subscribe(new Observer<ImageUpload>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        isUploading = false;
                    }

                    @Override
                    public void onNext(ImageUpload imageUpload) {
                        isUploading = false;
                        if (imageUpload.getMsg().equals("OK") && imageUpload.getStatus().equals("1")) {
                            mCurrUpImageItem.addTime = 1;
                            mCurrUpImageItem.name = imageUpload.getResult().getPic();
                            mRvAdapter.notifyDataSetChanged();
                            checkIsCanSubmit();
                        } else {
                            //上传失败
                            mImageItems.remove(mCurrUpImageItem);
                            mRvAdapter.notifyDataSetChanged();
                            ToastUitl.showShort("第" + (mCurrUpIndex + 1) + "张上传失败");
                            checkIsCanSubmit();
                        }
                    }
                });

    }


    public boolean isHaveAddItem() {
        boolean isAddItem = false;
        if (mImageItems != null && (mImageItems.size() > 0)) {
            isAddItem = TextUtils.isEmpty(mImageItems.get(mImageItems.size() - 1).path);
        }
        return isAddItem;
    }

    /**
     * 去除最后一个 addItem 如果有的话
     *
     * @return
     */
    public ArrayList<ImageItem> removeAddItem() {
        ArrayList<ImageItem> preImageItems = new ArrayList<>();
        preImageItems.addAll(mImageItems);
        if (isHaveAddItem()) {
            preImageItems.remove(mImageItems.size() - 1);
        }
        return preImageItems;
    }

    /**
     * 开启预览
     *
     * @param pos
     */
    public void startPreview(int pos) {
        Intent intentPreview = new Intent(getActivity(), ImagePreviewDelActivity.class);
        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, removeAddItem());
        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, pos);
        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
        getActivity().startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
    }


    /**
     * 是否删除此张图片
     */
    private void showDeleteDialog(final int pos) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示");
        builder.setMessage("要删除这张照片吗？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //移除当前图片刷新界面
                mImageItems.remove(pos);
                if (!isHaveAddItem()) {
                    mImageItems.add(mAddItem);
                }
                ;
                mRvAdapter.notifyDataSetChanged();
                checkIsCanSubmit();
            }
        });
        builder.show();
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }


    @OnClick({R.id.ll_contract_pre, R.id.bt_submit, R.id.ll_contract_down})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_submit:
                sumbit();
                break;
            case R.id.ll_contract_pre:
                getPreContract(1);
                break;
            case R.id.ll_contract_down:
                getPreContract(2);
                break;
        }
    }

    public void sumbit() {
        if (isUploading) {
            ToastUitl.showLong("正在上传图片");
            return;
        }
        showLoading();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("app_token", PreferenceUtils.getToken());
        if (mImageItems.size()<3){
            ToastUitl.showLong("合同页数至少2张");
            hideLoading();
            return;
        }
        for (int i = 0; i < mImageItems.size(); i++) {
            if (!TextUtils.isEmpty(mImageItems.get(i).name))
                hashMap.put("agreementPic" + (i + 1), mImageItems.get(i).name);
        }
        NetWork.getMaterialSubApi().saveAgreementPic(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ResponseBean>bindToLife())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showLong(e.toString());
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean bean) {
                        hideLoading();
                        if (Constant.OK_STATUS.equals(bean.getStatus())) {
                            ToastUitl.showLong("提交成功");
                            OpenCompanyEvent event = new OpenCompanyEvent(OpenCompanyEvent.TO_FINAL_AUDIT_PAGE);
                            event.auditStatus = AuditFragment.AuditStatus.AuditIng;
                            EventBus.getDefault().post(event);
                        } else {
                            ToastUitl.showLong(bean.getMessage());
                        }
                    }
                });
    }

    public void getPreContract(final int type) {
        showLoading();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("app_token", PreferenceUtils.getToken());
        NetWork.getMaterialSubApi().getAgreementPre(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ResponseBean<ContractPre>>bindToLife())
                .subscribe(new Observer<ResponseBean<ContractPre>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showLong(e.toString());
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean<ContractPre> bean) {
                        hideLoading();
                        if (Constant.OK_STATUS.equals(bean.getStatus())) {
                            ContractPre pre = bean.getParamer();
                            mContractDownUrl = pre.getAgreementServer() + pre.getAgreementDownloadUrl();
                            mContractPreUrl = Constant.BaseUrl_H5 + pre.getAgreementPreviewUrl();
                            try {
                                if (type == 1) {
                                    ToIntentUtil.toCommonIntent(mContractPreUrl, getActivity());
                                } else {
                                    Uri uri = Uri.parse(mContractDownUrl);
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(intent);
                                }
                            }catch (Exception e){
                                e.toString();
                            }

                        } else {
                            ToastUitl.showLong(bean.getMessage());
                        }
                    }
                });
    }


    public void checkIsCanSubmit() {
        if (mImageItems.size() > 1) {
            //代表有图片
            mBtSubmit.setClickable(true);
            mBtSubmit.setBackgroundResource(R.drawable.btn_audit_bg_blue);
        } else {
            mBtSubmit.setClickable(false);
            mBtSubmit.setBackgroundResource(R.drawable.btn_audit_bg_gray);
        }
    }


}
